package com.mohan.calligraphy.anno.impl;


import com.mohan.calligraphy.anno.CallParamValid;
import com.mohan.calligraphy.dto.SystemUserRegistry;
import com.mohan.calligraphy.util.BeanValidator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class CallParamValidImpl {

    @Pointcut("execution(* com.mohan.*.*.controller.*.*(..))")
    public void valid() {

    }

    @Before("valid()")
    public void doBefore(JoinPoint joinPoint) {
        Object[] params = joinPoint.getArgs();
        if (ArrayUtils.isEmpty(params)) {
            return;
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 参数注解，一维是参数，二维是注解
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            Object param = params[i];
            Annotation[] paramAnn = annotations[i];
            // 如果参数为空的话，那么就直接下一个参数
            if (param == null || paramAnn.length == 0) {
                continue;
            }
            for (Annotation annotation : paramAnn) {
                if (annotation.annotationType().equals(CallParamValid.class)){
                    BeanValidator.check(param);
                    break;
                }
            }
        }
    }
}
